package com.sunchen.asc.auth.service;

import com.sunchen.asc.auth.dto.SecurityUser;
import com.sunchen.asc.service.common.ResultResponse;
import com.sunchen.asc.service.common.ResultUtil;
import com.sunchen.asc.service.user.api.UserService;
import com.sunchen.asc.service.user.dto.UserDto;
import com.sunchen.asc.service.user.vo.NewUserVo;
import com.sunchen.asc.service.user.vo.UserVo;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

@Service
public class UserDetailService implements UserDetailsService {

    @DubboReference
    private UserService userService;
    @Autowired
    private PasswordEncoder passwordEncoder;

    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //@todo 根据用户名获取用户，数据库获取
        ResultResponse<UserDto> resultUserDto = userService.getUser(username);
        SecurityUser securityUser = null;
        //转换为登录用户信息
        if (resultUserDto.getCode()==200){
            securityUser = new SecurityUser(resultUserDto.getData());
        }else {
            throw new UsernameNotFoundException("USER_NOT_FOUND");
        }
        return securityUser;
    }
    public ResultResponse createUser(NewUserVo userVo){
        userVo.setPassword(passwordEncoder.encode(userVo.getPassword()));
        ResultResponse resultResponse = userService.creatUser(new UserDto(userVo));
        if (resultResponse.getCode()==200){
            return ResultUtil.success("用户创建成功");
        }else {
            return ResultUtil.failed();
        }
    }

}
